﻿using Memcached.ClientLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LightingCache
{
    public class CacheManager
    {
        private string[] _servers;
        private SockIOPool _pool;
        private MemcachedClient _client;

        private string[] Servers
        {
            get
            {
                return _servers;
            }
        }

        private SockIOPool Pool
        {
            get
            {
                if (_pool == null)
                {
                    _pool = SockIOPool.GetInstance();
                    _pool.SetServers(Servers);
                    _pool.InitConnections = 3;
                    _pool.MinConnections = 3;
                    _pool.MaxConnections = 5;
                    _pool.SocketConnectTimeout = 1000;
                    _pool.SocketTimeout = 3000;
                    _pool.MaintenanceSleep = 30;
                    _pool.Failover = true;
                    _pool.Nagle = false;
                }
                return _pool;
            }
        }

        private MemcachedClient Client
        {
            get
            {
                if(_client == null)
                {
                    _client = new MemcachedClient();
                    _client.EnableCompression = false;
                }
                return _client;
            }
        }

        public object this[string key]
        {
            get
            {
                return Client.Get(key);
            }
        }

        public CacheManager(string[] servers)
        {
            _servers = servers;
        }
        
        public void Initialize()
        {
            Pool.Initialize();
        }

        public void ShutDown()
        {
            Pool.Shutdown();
        }

        public void Add(string key, object value, DateTime dateTime)
        {
            Client.Add(key, value, dateTime);
        }

        public bool Contains(string key)
        {
            return Client.KeyExists(key);
        }
    }
}
